{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "69ced868",
   "metadata": {},
   "source": [
    "## Use of Tools for Agentic Workflow"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "731e1896",
   "metadata": {},
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv\n",
    "from agents import Agent, Runner, trace, function_tool\n",
    "from openai.types.responses import ResponseTextDeltaEvent\n",
    "from typing import Dict\n",
    "import sendgrid\n",
    "import os\n",
    "from sendgrid.helpers.mail import Mail, Email, To, Content\n",
    "import asyncio\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "cb5e4ac7",
   "metadata": {},
   "outputs": [],
   "source": [
    "instructions1 = \"You are a sales agent working for ComplAI, \\\n",
    "a company that provides a SaaS tool for ensuring SOC2 compliance and preparing for audits, powered by AI. \\\n",
    "You write professional, serious cold emails.\"\n",
    "\n",
    "instructions2 = \"You are a humorous, engaging sales agent working for ComplAI, \\\n",
    "a company that provides a SaaS tool for ensuring SOC2 compliance and preparing for audits, powered by AI. \\\n",
    "You write witty, engaging cold emails that are likely to get a response.\"\n",
    "\n",
    "instructions3 = \"You are a busy sales agent working for ComplAI, \\\n",
    "a company that provides a SaaS tool for ensuring SOC2 compliance and preparing for audits, powered by AI. \\\n",
    "You write concise, to the point cold emails.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "e4e3e061",
   "metadata": {},
   "outputs": [],
   "source": [
    "sales_agent1 = Agent(\n",
    "        name=\"Professional_Sales_Agent\",\n",
    "        instructions=instructions1,\n",
    "        model=\"gpt-4o-mini\",\n",
    ")\n",
    "\n",
    "sales_agent2 = Agent(\n",
    "        name=\"Engaging_Sales_Agent\",\n",
    "        instructions=instructions2,\n",
    "        model=\"gpt-4o-mini\",\n",
    ")\n",
    "\n",
    "sales_agent3 = Agent(\n",
    "        name=\"Busy_Sales_Agent\",\n",
    "        instructions=instructions3,\n",
    "        model=\"gpt-4o-mini\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "b04fc11f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Agent(name='Professional_Sales_Agent', instructions='You are a sales agent working for ComplAI, a company that provides a SaaS tool for ensuring SOC2 compliance and preparing for audits, powered by AI. You write professional, serious cold emails.', prompt=None, handoff_description=None, handoffs=[], model='gpt-4o-mini', model_settings=ModelSettings(temperature=None, top_p=None, frequency_penalty=None, presence_penalty=None, tool_choice=None, parallel_tool_calls=None, truncation=None, max_tokens=None, reasoning=None, metadata=None, store=None, include_usage=None, extra_query=None, extra_body=None, extra_headers=None, extra_args=None), tools=[], mcp_servers=[], mcp_config={}, input_guardrails=[], output_guardrails=[], output_type=None, hooks=None, tool_use_behavior='run_llm_again', reset_tool_choice=True)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sales_agent1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "ace061c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def send_email(body: str):\n",
    "    \"\"\" Send out an email with the given body to all sales prospects \"\"\"\n",
    "    sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))\n",
    "    from_email = Email(\"toyeladun@gmail.com\")  # Change to your verified sender\n",
    "    to_email = To(\"toyeladun@gmail.com\")  # Change to your recipient\n",
    "    content = Content(\"text/plain\", body)\n",
    "    mail = Mail(from_email, to_email, \"Sales email\", content).get()\n",
    "    sg.client.mail.send.post(request_body=mail)\n",
    "    return {\"status\": \"success\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "623afb84",
   "metadata": {},
   "source": [
    "Wrap agents in a tool -Method one - List out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "6b838d59",
   "metadata": {},
   "outputs": [],
   "source": [
    "#wrap the agents in a tool\n",
    "message = \"Write a cold sales email\"\n",
    "\n",
    "tool1 = sales_agent1.as_tool(tool_name=\"salesagent1\", tool_description=\"message\")\n",
    "tool2 = sales_agent2.as_tool(tool_name=\"salesagent2\", tool_description=\"message\")\n",
    "tool3 = sales_agent3.as_tool(tool_name=\"salesagent3\", tool_description=\"message\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ea03b8b",
   "metadata": {},
   "source": [
    "Wrap agents in a tool -Method two -run a loop and store in a list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "12093b85",
   "metadata": {},
   "outputs": [],
   "source": [
    "message = \"Write a cold sales email\"\n",
    "\n",
    "\n",
    "allagents = [sales_agent1, sales_agent2, sales_agent3]\n",
    "\n",
    "tools = [agent.as_tool(tool_name=agent.name, tool_description=message) for agent in allagents]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "4ee3a613",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[FunctionTool(name='Professional_Sales_Agent', description='Write a cold sales email', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'Professional_Sales_Agent_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x000001ADF2939B20>, strict_json_schema=True, is_enabled=True),\n",
       " FunctionTool(name='Engaging_Sales_Agent', description='Write a cold sales email', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'Engaging_Sales_Agent_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x000001ADF2EC0C20>, strict_json_schema=True, is_enabled=True),\n",
       " FunctionTool(name='Busy_Sales_Agent', description='Write a cold sales email', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'Busy_Sales_Agent_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x000001ADF2EC1B20>, strict_json_schema=True, is_enabled=True)]"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "975d5364",
   "metadata": {},
   "outputs": [],
   "source": [
    "#append the sendgrid tool to the allagents list of tools making it four tools\n",
    "#-3 email generation agents \n",
    "#-1 email sendgrid agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "02dcb1ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools.append(send_email)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "7168ae21",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[FunctionTool(name='Professional_Sales_Agent', description='Write a cold sales email', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'Professional_Sales_Agent_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x000001ADF2939B20>, strict_json_schema=True, is_enabled=True),\n",
       " FunctionTool(name='Engaging_Sales_Agent', description='Write a cold sales email', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'Engaging_Sales_Agent_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x000001ADF2EC0C20>, strict_json_schema=True, is_enabled=True),\n",
       " FunctionTool(name='Busy_Sales_Agent', description='Write a cold sales email', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'Busy_Sales_Agent_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x000001ADF2EC1B20>, strict_json_schema=True, is_enabled=True),\n",
       " FunctionTool(name='send_email', description='Send out an email with the given body to all sales prospects', params_json_schema={'properties': {'body': {'title': 'Body', 'type': 'string'}}, 'required': ['body'], 'title': 'send_email_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x000001ADF2E5EC00>, strict_json_schema=True, is_enabled=True)]"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b549cb58",
   "metadata": {},
   "source": [
    "Lastly , we use the final agent to plan orchestration amongst these other agents/tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c652fd11",
   "metadata": {},
   "outputs": [],
   "source": [
    "managerinstructions = \"\"\"\n",
    "You are a Sales Manager at ComplAI. Your goal is to find the single best cold sales email using the sales_agent tools.\n",
    " \n",
    "Follow these steps carefully:\n",
    "1. Generate Drafts: Use all three sales_agent tools to generate three different email drafts. Do not proceed until all three drafts are ready.\n",
    " \n",
    "2. Evaluate and Select: Review the drafts and choose the single best email using your judgment of which one is most effective.\n",
    " \n",
    "3. Use the send_email tool to send the best email (and only the best email) to the user.\n",
    " \n",
    "Crucial Rules:\n",
    "- You must use the sales agent tools to generate the drafts — do not write them yourself.\n",
    "- You must send ONE email using the send_email tool — never more than one.\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "planningagent = Agent(\n",
    "    name = \"Sales_Manager\",\n",
    "    instructions=managerinstructions,\n",
    "    tools=tools,\n",
    "    model='gpt-4o-mini'\n",
    ")\n",
    "\n",
    "\n",
    "with trace(\"Sales email picker\"):\n",
    "    result = await Runner.run(planningagent, \"Send a cold email\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "619c73c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(result.final_output)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
